import {
  DiskStorage,
  DiskStorageFile,
  FileFieldsInterceptor,
  FileInterceptor,
  FilesInterceptor,
  MemoryStorageFile,
  UploadedFile,
  UploadedFiles,
} from '@blazity/nest-file-fastify';
import { Public } from '@libs/common/decorator';
import { Controller, Post, UseInterceptors } from '@nestjs/common';
import { resolve } from 'path';

const PATH_UPLOADS = resolve('uploads');

@Controller('files')
export class FilesController {
  @Post('single')
  @Public()
  @UseInterceptors(FileInterceptor('file'))
  async uploadSingle(@UploadedFile() file: MemoryStorageFile) {
    // 单个文件上传 - 内存存储
    return file;
  }

  @Post('single-disk')
  @Public()
  @UseInterceptors(FileInterceptor('file', { dest: PATH_UPLOADS }))
  public async uploadSingleToDisk(@UploadedFile() file: DiskStorageFile) {
    console.log(file.path);
    // 单个文件上传 - 磁盘存储
    return file;
  }

  @Post('array')
  @Public()
  @UseInterceptors(FilesInterceptor('files', 99))
  uploadArray(
    @UploadedFiles()
    files: MemoryStorageFile[],
  ) {
    // 多个文件上传 - 内存存储
    return files;
  }

  @Post('multi')
  @Public()
  @UseInterceptors(
    FileFieldsInterceptor([
      { name: 'files', maxCount: 1 },
      { name: 'images', maxCount: 2 },
    ]),
  )
  public async uploadMultipleFields(
    @UploadedFiles()
    files: {
      files: MemoryStorageFile[];
      images: MemoryStorageFile[];
    },
  ) {
    return files;
  }

  @Post('temp')
  @Public()
  @UseInterceptors(
    FileInterceptor('file', {
      storage: new DiskStorage({
        dest: PATH_UPLOADS,
        removeAfter: true,
      }),
    }),
  )
  public async uploadAndRemove(@UploadedFile() file: DiskStorageFile) {
    console.log(file.size);
    // 临时文件上传 - 磁盘存储
    return file;
  }
}
